// import React from "react";
import React, { useState, useEffect } from "react";
import marked from "marked";
import hljs from "highlight.js";
import moment from 'moment'; 
import "highlight.js/styles/monokai-sublime.css";
// import ReactMarkdown from 'react-markdown'
import { Row, Col, Input, Select, Button, DatePicker, message, Spin } from "antd";
import axios from "axios";
import servicePath from "../config/apiUrl";

import "../static/css/AddArticle.css";

const { Option } = Select;
const { TextArea } = Input;

function AddArticle(props) {
  const [articleId, setArticleId] = useState(0); // 文章的ID，如果是0说明是新增加，如果不是0，说明是修改
  const [articleTitle, setArticleTitle] = useState(""); //文章标题
  const [articleImg, setArticleImg] = useState(""); //文章beijing
  const [articleContent, setArticleContent] = useState(""); //markdown的编辑内容
  const [markdownContent, setMarkdownContent] = useState("预览内容"); //html内容
  const [introducemd, setIntroducemd] = useState(); //简介的markdown内容
  const [introducehtml, setIntroducehtml] = useState("等待编辑"); //简介的html内容
  const [showDate, setShowDate] = useState(); //发布日期
  const [defaultValue,setDefaultValue] = useState();  //默认时间
  const [updateDate, setUpdateDate] = useState(); //修改日志的日期 
  const [spinning, setSpinning] = useState(false); // loading
  const [typeInfo, setTypeInfo] = useState([]); // 文章类别信息
  const [selectedType, setSelectType] = useState(); //选择的文章类别
  // setIsLoadding(true);
  useEffect(() => {
    getTypeInfo();
    setDefaultValue(new Date())
    setShowDate(new Date())
    
    //获得文章ID
    // console.log('66666666666666',props.location.typeName.type_id);
    
    let tmpId = props.match.params.id
    if(tmpId){
        setUpdateDate(new Date())
        setArticleId(tmpId)
        setSelectType(props.location.typeName.type_id?props.location.typeName.type_id:'')
        getArticleById(tmpId)
    } 
  }, []);
  marked.setOptions({
    renderer: new marked.Renderer(), //这个是必须填写的，你可以通过自定义的Renderer渲染出自定义的格式
    gfm: true, //启动类似Github样式的Markdown,填写true或者false
    pedantic: false, //只解析符合Markdown定义的，不修正Markdown的错误。填写true或者false
    sanitize: false, //原始输出，忽略HTML标签，这个作为一个开发人员，一定要写flase
    tables: true, //支持Github形式的表格，必须打开gfm选项
    breaks: false, //支持Github换行符，必须打开gfm选项，填写true或者false
    smartLists: true, //优化列表输出，这个填写ture之后，你的样式会好看很多，所以建议设置成ture
    smartypants: false, //高亮显示规则 ，这里我们将使用highlight.js来完成
    highlight: function(code) {
      //code 参数是<code>中的初始内容， 该函数返回的是经highlight 处理 （给特定内容添加上class）后的内容。
      return hljs.highlightAuto(code).value;
    }
  });
  const changeContent = e => {
    setArticleContent(e.target.value);
    let html = marked(e.target.value);
    setMarkdownContent(html);
  };
  const changeIntroduce = e => {
    setIntroducemd(e.target.value);
    let html = marked(e.target.value);
    setIntroducehtml(html);
  };
  const markedContent = () => {
    setTimeout(() => {
      let html = marked(articleContent);
      setMarkdownContent(html);
      // setIsLoadding(false);
      message.success("转换完成");
    }, 300);
  };
  const getArticleById = id => {
    axios(servicePath.getArticleById + id, {
      withCredentials: false,
      header: { "Access-Control-Allow-Origin": "*" }
    }).then(res => {
      //let articleInfo= res.data.data[0]
      console.log(res,"resssss");
      
      setArticleTitle(res.data.data[0].title);
      setArticleImg(res.data.data[0].articleImg);
      setArticleContent(res.data.data[0].article_content);
      let html = marked(res.data.data[0].article_content);
      setMarkdownContent(html);
      setDefaultValue(res.data.data[0].addTime)
      setIntroducemd(res.data.data[0].introduce);
      let tmpInt = marked(res.data.data[0].introduce);
      setIntroducehtml(tmpInt);
      setShowDate(res.data.data[0].addTime);
      // setUpdateDate(res.data.data[0].addTime);
      // setSelectType(res.data.data[0].typeId);
    }).catch((err)=>{
      message.error(err.response.data.data)
      if(err.response.status === 401){
        props.history.push("/login")
      }
      setSpinning(false)
    })
  };

  //选择类别
  const selectTypeHandler = value => {
    setSelectType(value);
  };
  const saveArticle = () => {
    markedContent(); //先进行转换
    console.log(articleTitle, "articleTitle");

    if (!selectedType) {
      message.error("必须选择文章类别");
      return false;
    } else if (!articleTitle) {
      message.error("文章名称不能为空");
      return false;
    } else if (!articleContent) {
      message.error("文章内容不能为空");
      return false;
    } else if (!introducemd) {
      message.error("简介不能为空");
      return false;
    } else if (!showDate) {
      message.error("发布日期不能为空");
      return false;
    } else if (!articleImg) {
      message.error("文章背景不能为空");
      return false;
    }
    message.success("检验通过");
    let dataProps = {}; //传递到接口的参数
    dataProps.type_id = selectedType;
    dataProps.title = articleTitle;
    dataProps.article_content = articleContent;
    dataProps.introduce = introducemd;
    dataProps.articleImg = articleImg;

    if (articleId === 0) {
      dataProps.addTime = showDate;
      dataProps.view_count = Math.ceil(Math.random() * 100) + 1000;
      axios({
        method: "post",
        url: servicePath.addArticle,
        data: dataProps,
        withCredentials: false
      }).then(res => {
        setArticleId(res.data.insertId);
        if (res.data.isScuccess) {
          message.success("文章保存成功");
          props.history.push("/index/list/")
        } else {
          message.error(res.data.isError);
        }
      }).catch((err)=>{
        message.error(err.response.data.data)
        if(err.response.status === 401){
          props.history.push("/login")
        }
        setSpinning(false)
      })
    } else {
      dataProps.updateTime = new Date(updateDate).getTime();
      dataProps.id = articleId;
      axios({
        method: "post",
        url: servicePath.updateArticle,
        header: { "Access-Control-Allow-Origin": "*" },
        data: dataProps,
        withCredentials: false
      }).then(res => {
        if (res.data.isScuccess) {
          message.success("文章保存成功");
          props.history.push("/index/list/")
        } else {
          message.error("保存失败");
        }
      }).catch((err)=>{
        message.error(err.response.data.data)
        if(err.response.status === 401){
          props.history.push("/login")
        }
        setSpinning(false)
      })
    }
  };
  //从中台得到文章类别信息
  const getTypeInfo = () => {
    setSpinning(true)
    axios({
      method: "get",
      url: servicePath.getTypeInfo,
      header: { "Access-Control-Allow-Origin": "*" },
      withCredentials: false
    }).then(res => {
      //  console.log(res.data);
      if (res.data.data === "没有登录") {
        sessionStorage.removeItem("openId");
        sessionStorage.removeItem("userName");
        props.history.push("/login")
      } else {
        setTypeInfo(res.data.data)
        setSpinning(false)
      }
    }).catch((err)=>{
      message.error(err.response.data.data)
      if(err.response.status === 401){
        props.history.push("/login")
      }
      setSpinning(false)
    })
  };
  return (
    <div>
      <Spin tip="Loading..." spinning={ spinning }>
        <Row gutter={5}>
          <Col span={18}>
            <Row gutter={10}>
              <Col span={20}>
                <Input
                  value={articleTitle}
                  placeholder="博客标题"
                  onChange={e => {
                    setArticleTitle(e.target.value);
                  }}
                  size="large"
                />
              </Col>
              <Col span={4}>
                &nbsp;
                <Select
                  value={ selectedType }
                  size="large"
                  placeholder="请选择类别"
                  onChange={selectTypeHandler}
                >
                  {typeInfo.map((item, index) => {
                    return (
                      <Option key={index} value={item.id}>
                        {item.typeName}
                      </Option>
                    );
                  })}
                </Select>
              </Col>
            </Row>
            <br />
            <Row gutter={10}>
              <Col span={12}>
                <TextArea
                  value={articleContent}
                  className="markdown-content"
                  rows={35}
                  onChange={changeContent}
                  onPressEnter={changeContent}
                  placeholder="文章内容"
                />
                {/* <div 
                    className="show-html"
                    dangerouslySetInnerHTML = {{__html:markdownContent}} >

                </div> */}
              </Col>
              <Col span={12}>
                {/* <ReactMarkdown source={markdownContent} escapeHtml={false}  /> */}
                <div
                  className="show-html"
                  dangerouslySetInnerHTML={{ __html: markdownContent }}
                ></div>
              </Col>
            </Row>
          </Col>

          <Col span={6}>
            <Row>
              <Col span={24}>
                <Button size="large" onClick={markedContent}>
                  转换内容
                </Button>
                &nbsp;
                <Button type="primary" size="large" onClick={saveArticle}>
                  发布文章
                </Button>
                <br />
              </Col>
              <Col span={24}>
                
                <br />
                <Input
                  value={articleImg}
                  placeholder="博客背景"
                  onChange={e => {
                    setArticleImg(e.target.value);
                  }}>
                  
                </Input>
                <br />
                <TextArea
                  rows={4}
                  value={introducemd}
                  onChange={changeIntroduce}
                  onPressEnter={changeIntroduce}
                  placeholder="文章简介"
                />
                <div
                  className="introduce-html"
                  dangerouslySetInnerHTML={{
                    __html: "文章简介：" + introducehtml
                  }}
                ></div>
              </Col>
              <Col span={12}>
                <div className="date-select">
                  <DatePicker
                    onChange={(dateString) => {setShowDate(dateString)}}
                    value={showDate ? moment(showDate, 'YYYY-MM-DD') : undefined}
                    placeholder="发布日期"
                    size="large"
                  />
                </div>
              </Col>
              <Col span={12}>
                <div className="date-select">
                  <DatePicker size="large" onChange={(dateString) => setUpdateDate(dateString)} placeholder="修改日期" value={updateDate ? moment(updateDate, 'YYYY-MM-DD') : undefined} />
                </div>
              </Col>
            </Row>
          </Col>
        </Row>
      </Spin>
    </div>
  );
}

export default AddArticle;
